package com.hxzy.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

/**
 * @Author wy
 * @Description 局部拦截器的名称  RequestLog
 * @Date 2023/10/16 17:19
 * @Version 1.0
 */
@Log4j2
@Component
public class RequestLogGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestLogGatewayFilterFactory.ParamsConfig> {

    /**
     * 这里必须要配置，不能省略
     */
    public RequestLogGatewayFilterFactory() {
        super(ParamsConfig.class);
    }

    /**
     * 拦截器的名称
     * @return
     */
    @Override
    public String name() {
        //默认名称，  RequestLog  ( GatewayFilterFactory)删除掉
        return super.name();
    }

    @Override
    public GatewayFilter apply(ParamsConfig config) {
        log.info( config.getParamName()+","+config.getParamValue());
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 获取请求路径
                URI uri = exchange.getRequest().getURI();
                log.info("获取到请求路径：{}", uri.toString());

                //获取请求头
                HttpHeaders headers = exchange.getRequest().getHeaders();
                String authorization = headers.getFirst("Authorization");

                log.info("获取到请求头信息：{}", authorization);

                return chain.filter(exchange);

            }
        };
    }



    public static class ParamsConfig {
        private String paramName;

        private String paramValue;

        public String getParamName() {
            return paramName;
        }

        public void setParamName(String paramName) {
            this.paramName = paramName;
        }

        public String getParamValue() {
            return paramValue;
        }

        public void setParamValue(String paramValue) {
            this.paramValue = paramValue;
        }
    }
}
